package com.gwq.controller;

import com.gwq.base.ResponseData;
import com.gwq.common.FileCheck;
import com.gwq.dto.ExercisesDto;
import com.gwq.entity.Message;
import com.gwq.param.*;
import com.gwq.service.ComputedService;
import com.gwq.service.ExercisesService;
import com.gwq.utils.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Api(description = "算式管理")
@RestController
@CrossOrigin
@RequestMapping("/example")
public class ExampleController {

    @Resource
    private ComputedService computedService;
    @Resource
    private ExercisesService exercisesService;

    @ApiOperation(value="生成算式")
    @PostMapping("/computed")
    public ResponseData example(@RequestBody ExerciseParam exerciseParam, Principal principal){
        return ResponseData.success(computedService.example(exerciseParam,principal));
    }

    @ApiOperation(value="文件算式")
    @PostMapping("/file")
    public void file(@RequestBody ExerciseParam exerciseParam, HttpServletResponse response, HttpServletRequest request , Principal principal){
        try{

            ExercisesDto example = computedService.example(exerciseParam,principal);


            File file = FileUtils.creatFile(example);


            exercisesService.updateExercises(example.getId(),file.getName());

            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            String filename = file.getName();
            fis.read(buffer);
            fis.close();
            // 清空response
//            response.reset();
            // 设置response的Header
            response.setContentType("text/html;charset=utf-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            filename= FileUtils.filenameEncoding(filename,request);
            //URLEncoder.encode(filename,"utf-8")
            response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("UTF-8"), "ISO8859-1"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    //上传文件
    @ApiOperation(value="上传文件算式")
    @PostMapping("/upload")
    @FileCheck(typeCheckErrorMsg = "不支持的文件格式", supportedSuffixes = {"txt"}, type = FileCheck.CheckType.SUFFIX)
    public ResponseData uploadPicture(MultipartFile verticalPicture, Principal principal) throws IOException {
        return computedService.upload(verticalPicture,principal);

    }

    @ApiOperation(value="批改答案")
    @PostMapping("/check")
    public ResponseData check(@RequestBody ExEqualsParam exEqualsParam, Principal principal){
        return computedService.exEquals(exEqualsParam,principal);
    }

    @ApiOperation(value="查看习题历史记录")
    @GetMapping("/page")
    public ResponseData list(ExercisesPageParam exercisesPageParam, Principal principal){
        return ResponseData.success("查询成功！",exercisesService.listHistoryExercises(exercisesPageParam,principal));
    }

    @ApiOperation(value="查看习题详情")
    @GetMapping("/{exercisesId}")
    public ResponseData getByMessageId(@PathVariable String exercisesId){
        return ResponseData.success("查询成功！",exercisesService.getHistoryExercises(exercisesId));
    }

    @ApiOperation(value="设置习题时间")
    @PostMapping("/date")
    public ResponseData setDate(@RequestBody ExDateParam exDateParam, Principal principal){
        computedService.exSettingDate(exDateParam,principal);
        return ResponseData.success("设置成功！");
    }

    @ApiOperation(value="查看设置时间")
    @GetMapping("/getDate")
    public ResponseData getDate(){
        return ResponseData.success("查询成功！",computedService.getExDate());
    }
}
